/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentPage;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.*;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.core.LayoutManager;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.exception.OwnerNotFoundException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.VirtualFolderForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.core.LinkedObjectsInfoContainer;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.util.ModuleUtils;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Moves content page folder.
 * </p>
 * <p><a href="UpdateContentPageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.2 $ $Date: 2007/12/19 21:09:02 $
 * @struts.action path="/core/contentPage/moveFolder"
 * name="virtualFolderForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentPage-update"
 * @struts.action-forward name="inputForward"
 * path=".core.contentPage.moveFolder"
 * @struts.action-forward name="listContentPages"
 * path="/core/contentPage/list.do"
 * redirect="true"
 * @struts.action-forward name="viewLinkedObjects"
 * path="/core/linkedObjects/view.do"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentPage/list.do"
 */
public final class MoveContentPageFolderAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        if ( !isCancelled(request) ) {
            // flag shows whether to force changing of URI if there're some
            // linked objects
            boolean force = "true".equalsIgnoreCase(request.getParameter("force"));

            VirtualFolderForm virtualFolderForm;
            if (force) {
                virtualFolderForm = (VirtualFolderForm) session.getAttribute(WebappConstants.VIRTUAL_FOLDER_FORM_KEY);
            } else {
                virtualFolderForm = (VirtualFolderForm) form;
            }
            String path = virtualFolderForm.getPath();
            String initialPath = path;

            if ( path == null || path.equals("/") ) {
                path = "";
            }

            // ensure, that current folder starts with slash and does not end with slash
            if ( path.length() > 0 ) {
                if ( !path.startsWith("/") ) {
                    path = "/" + path;
                }
                if ( path.endsWith("/") ) {
                    path = path.substring(0, path.length() - 1);
                }
            }

            String newPath = virtualFolderForm.getNewPath();
            if ( newPath == null || newPath.equals("/") ) {
                newPath = "";
            }

            // ensure, that new path starts with slash and does not end with slash
            if ( newPath.length() > 0 ) {
                if ( !newPath.startsWith("/") ) {
                    newPath = "/" + newPath;
                }
                if ( newPath.endsWith("/") ) {
                    newPath = newPath.substring(0, newPath.length() - 1);
                }
            }

            // get all content pages, which exist in given folder
            String whereClause = "page.uri like '" + StringUtil.sqlEscape(WebappConstants.CONTENT_PAGES_URI_PREFIX + path + "/") + "%'";
            QueryInfo queryInfo = new QueryInfo();
            queryInfo.setWhereClause(whereClause);

            PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
            PartialCollection contentPages = pageManager.listContentPages(queryInfo);

            if (contentPages.isEmpty()) {
                // content pages not found. they might be deleted by someone else
                ActionMessages errors = new ActionMessages();
                errors.add("virtualFolderIsEmpty", new ActionMessage("core.virtialFolder.errors.empty"));
                saveErrors(request, errors);
                return mapping.findForward("listContentPages");
            }

            // collecting IDs of used pages
            List usedPagesIds = new ArrayList();
            for (Iterator i = contentPages.iterator(); i.hasNext(); ) {
                ContentPage contentPage = (ContentPage) i.next();
                if (contentPage.isInUse()) {
                    usedPagesIds.add(contentPage.getId());
                }
            }
                        
            if (!force && !usedPagesIds.isEmpty() ) {
                // trying to change URI of used pages - display warning
                String action = mapping.findForward("listContentPages").getPath();
                String redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
                session.setAttribute(WebappConstants.VIRTUAL_FOLDER_FORM_KEY, virtualFolderForm);
                ActionMessages messages = new ActionMessages();
                messages.add("changeUriWarning", new ActionMessage("core.contentPage.messages.folderChangeUriWarning"));
                saveMessages(request, messages);

                LinkedObjectsInfoContainer container = new LinkedObjectsInfoContainer();
                container.setRedirectUrl(redirectUrl);
                container.setPath(initialPath);
                container.setNewPath(virtualFolderForm.getNewPath());
                container.setUpdateAction(mapping.getPath());
                container.setObjectsIds(usedPagesIds);
                container.setObjectType(LinkedObjectsInfoContainer.TYPE_PAGE);
                session.setAttribute(WebappConstants.LINKED_OBJECTS_INFO_CONTAINER_KEY, container);

                return mapping.findForward("viewLinkedObjects");
            }

            CacheUtil cacheUtil = CacheUtil.getInstance(request);
            SearchManager searchManager = SearchManager.getInstance(session.getServletContext());
            LayoutManager layoutManager = (LayoutManager) getBean(Constants.LAYOUT_MANAGER_BEAN);
            ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig(request, getServlet().getServletContext());
            String prefix = moduleConfig.getPrefix();
            if (log.isDebugEnabled()) {
                log.debug("Prefix: " + prefix);
            }

            boolean someAlreadyExist = false;
            boolean someWereUpdated = false;
            boolean someHasIncorrectUri = false;
            boolean someOwnerNotFound = false;

            for (Iterator contentPagesIterator = contentPages.iterator(); contentPagesIterator.hasNext(); ) {
                ContentPage contentPage = (ContentPage) contentPagesIterator.next();
                // this is done to obtain full page info (title, keywords...)
                contentPage = pageManager.retrieveContentPage(contentPage.getId());
                if (contentPage == null) {
                    continue;
                }

                //setup uri
                String uri = contentPage.getUri();
                String oldUri = uri;
                uri = uri.substring(WebappConstants.CONTENT_PAGES_URI_PREFIX.length());
                uri = uri.substring(path.length());
                uri = newPath + uri;
                uri = WebappConstants.CONTENT_PAGES_URI_PREFIX + uri;

                // check URI. If there is an action with the same path, return error
                String actionPath = prefix + uri;

                if (log.isDebugEnabled()) {
                    log.debug("Searching for action with path=" + actionPath);
                }

                if (moduleConfig.findActionConfig(actionPath) != null) {
                    // action with same uri exists
                    if (log.isDebugEnabled()) {
                        log.debug("Action was found - skipping");
                    }
                    someHasIncorrectUri = true;
                    continue;
                }

                // check whether there is already another content page with this URI
                ContentPage oldPage = pageManager.findContentPageByUri(uri);
                if (oldPage != null) {
                    // content page already exists
                    someAlreadyExist = true;
                    continue;
                }

                contentPage.setUri(uri);

                // remove links to this content page from unmodifiable menu items
                for (Iterator i = contentPage.getLinkedMenuItems().iterator(); i.hasNext();)
                {
                    MenuItem menuItem = (MenuItem) i.next();
                    if (!menuItem.isDynamic()) {
                        i.remove();
                    }
                }

                try {
                    pageManager.updateContentPage(contentPage, contentPage.getLayout().getId());

                    //reindex content page
                    Layout layout = layoutManager.retrieveLayout(contentPage.getLayout().getId());
                    searchManager.unIndexPage(oldUri, request);
                    if (contentPage.getActive().booleanValue()) {
                        searchManager.indexPage(contentPage, request);
                    }

                    // update cache
                    // flush all fields' and sequences' cache
                    cacheUtil.flushPageFieldValueCache(oldUri);
                    cacheUtil.flushPageSequenceCache(oldUri);
                    cacheUtil.flushContentPageCache(oldUri);

                    //put CP in cache
                    if (contentPage.getActive().booleanValue()) {
                        CacheUtil.ContentPageData cpd = new CacheUtil.ContentPageData(contentPage.getId(), layout.getCpDefinition(), WebappUtil.rolesToString(contentPage.getRoles()), contentPage.getCacheMaxAge());
                        cacheUtil.putContentPageInCache(cpd, uri);
                    }

                    // recache all fields
                    List fields = contentPage.getContentFields();
                    for (Iterator i = fields.iterator(); i.hasNext();) {
                        ContentField field = (ContentField) i.next();
                        List cfvList = field.getContentFieldValues();
                        for (Iterator j = cfvList.iterator(); j.hasNext();)
                        {
                            ContentFieldValue fieldValue = (ContentFieldValue) j.next();
                            String content;
                            if (field.getType() == ContentField.LINE_TYPE) {
                                content = fieldValue.getSimpleValue();
                            } else
                            if (field.getType() == ContentField.MULTILINE_TYPE) {
                                content = ConvertUtil.convertToString(fieldValue.getValue());
                            } else /* if HTML_TYPE */ {
                                content = ConvertUtil.convertToString(fieldValue.getValue());
                            }
                            CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId(), contentPage.getId());
                            cacheUtil.putPageFieldValueInCache(cfvData, contentPage.getUri(), field.getIdentifier(), fieldValue.getContentLocale().getIdentifier());
                        }
                    }

                    // recache all sequences
                    List sequences = contentPage.getSequences();
                    for ( Iterator i = sequences.iterator(); i.hasNext(); ) {
                        Sequence sequence = (Sequence) i.next();
                        CacheUtil.SequenceData sequenceData = new CacheUtil.SequenceData(sequence.getId());
                        cacheUtil.putPageSequenceInCache(sequenceData, contentPage.getUri(), sequence.getIdentifier());
                    }

                    if (force) {
                        // reindex and update cache for linked objects, because they
                        // were changed

                        // flush cache related to menu items
                        cacheUtil.flushMenuCache();
                        cacheUtil.flushContentPageCache();

                        // put linked values in cache and into search index
                        List linkedContentFieldValues = contentPage.getLinkedContentFieldValues();
                        Set owners = new HashSet();
                        for (Iterator i = linkedContentFieldValues.iterator(); i.hasNext();)
                        {
                            ContentFieldValue fieldValue = (ContentFieldValue) i.next();
                            ContentField field = fieldValue.getContentField();
                            Localizable owner = field.getOwner();
                            // put owner to set of owners to cache/reindex them later
                            owners.add(owner);

                            String localeIdentifier = fieldValue.getContentLocale().getIdentifier();

                            byte fieldType = field.getType();
                            String content;

                            if (fieldType == ContentField.LINE_TYPE) {
                                content = fieldValue.getSimpleValue();
                            } else {
                                content = ConvertUtil.convertToString(fieldValue.getValue());
                            }
                            if (owner instanceof Page) {
                                Page page = (Page) owner;
                                CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId(), owner.getId());
                                cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
                            }
                        }

                        // process owners
                        for (Iterator i = owners.iterator(); i.hasNext();) {
                            Localizable owner = (Localizable) i.next();
                            if (owner instanceof Layout) {
                                layout = (Layout) owner;
                                cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

                                //TODO: add into search index for every content page of the layout.
                                //TODO: add into index action pages
                                List layoutContentPages = layout.getContentPages();
                                for (int j = 0; j < layoutContentPages.size(); j++) {
                                    ContentPage cp = (ContentPage) layoutContentPages.get(j);
                                    searchManager.reIndexPage(cp, request);
                                    cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
                                }

                            } else if (owner instanceof Page) {
                                Page page = (Page) owner;
                                if (!contentPage.getId().equals(page.getId())) {
                                    searchManager.reIndexPage(page, request);
                                }
                                if (page instanceof ContentPage) {
                                    cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
                                }
                            }
                        }
                    }
                } catch (OwnerNotFoundException e) {
                    // layout not found. it might has already been deleted by another transaction
                    someOwnerNotFound = true;
                } catch (BeanAlreadyExistsException e) {
                    // content page already exists
                    someAlreadyExist = true;
                } catch (ObjectOptimisticLockingFailureException e) {
                    // content page was updated or deleted by another transaction
                    someWereUpdated = true;
                }
            }

            cacheUtil.flushFieldIndices();

            ActionMessages errors = new ActionMessages();
            if (someAlreadyExist) {
                // some content page already exists
                errors.add("someContentPageAlreadyExists", new ActionMessage("core.contentPage.errors.someAlreadyExists"));
            }
            if (someWereUpdated) {
                // some content page was updated or deleted by another transaction
                errors.add("someUpdateFailed", new ActionMessage("core.contentPage.errors.someUpdateFailed"));
            }
            if (someHasIncorrectUri) {
                // some content page has incorrect URI
                errors.add("someContentPageIncorrectUri", new ActionMessage("core.contentPage.errors.someIncorrectUri"));
            }
            if (someOwnerNotFound) {
                // owner of some content page was not found
                errors.add("someOwnerNotFound", new ActionMessage("core.contentPage.errors.someOwnerNotFound"));
            }
            if (someAlreadyExist || someWereUpdated
                    || someHasIncorrectUri || someOwnerNotFound) {
                saveErrors(request, errors);
            }

        }
        
        return mapping.findForward("listContentPages");
    }
}